#include <string.h>
#include "ioevent.h"
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "log.h"
#include <sys/epoll.h>

extern int io_epfd;

IoEvents::IoEvents() : protocol(-1), session_handler(NULL) {}
int IoEvents::init_events(int fd, char *ip, int type, BaseSession *handler)
{
	if (this->session_handler != NULL)
	{
		return -1;
	}
	this->protocol = type;
	if (type == 1)
	{
		this->session_handler = new RtspSession();
		this->session_handler->init_session(fd, ip);
	}
	else if (type == 2)
	{
		this->session_handler = new RtpSession();
		this->session_handler->init_session(fd, ip);
	}
	else if (type == 3)
	{
		this->session_handler = new RtcpSession();
		this->session_handler->init_session(fd, ip);
	}
	else if (type == 0 && handler != NULL) // 定时器类型
	{
		this->session_handler = handler;
	}

	this->set_nonblock(fd);
	modify_event(io_epfd, fd, EPOLLET | EPOLLIN | EPOLLERR, EPOLL_CTL_ADD);
	return 0;
}

int IoEvents::set_nonblock(int fd)
{
	int flags = fcntl(fd, F_GETFL, 0);
	if (flags < 0)
	{
		LOG("fcntl failed %s\n", strerror(errno));
		return -1;
	}
	if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0)
	{
		LOG("fcntl failed %s\n", strerror(errno));
		return -1;
	}

	return 0;
}